package com.hilihili.controller.detailComponent;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;

import com.hilihili.domain.dto.CommentLimitDTO;
import com.hilihili.domain.entity.CommentLikeUser;
import com.hilihili.service.ICommentLikeUserService;
import com.hilihili.util.DateChangeUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.hilihili.domain.entity.Comment;
import com.hilihili.service.ICommentService;

/**
 * 评论Controller
 *
 * @author xhc
 * @date 2023-11-15
 */
@RestController
@RequestMapping("/hilihili/comment")
public class CommentController extends BaseController
{
    @Autowired
    private ICommentService commentService;
    @Autowired
    private ICommentLikeUserService commentLikeUserService;

    /**
     * 查询子评论
     * 前端参数：
     *          {videoId: this.$route.params.id, id:this.commentId ,startIndex:pageNum ,maxCount:pageSize}
     * 计算下标 ：offset = (pageNum - 1) * pageSize
     * @param
     * @return
     */
    @GetMapping("/getCommentChildren")
    public AjaxResult getCommentChildrenList(CommentLimitDTO commentLimitDTO){

        Map<String, Object> commentChildren = commentService.getCommentChildren(commentLimitDTO);
        return AjaxResult.success(commentChildren);
    }
    /**
     * 查询关于 视频id 查询所有  一级评论
     * @param
     * @return
     */
    @GetMapping("/getCommentByvideo")
    public AjaxResult getCommentByvideo(CommentLimitDTO commentLimitDTO)
    {
        if (commentLimitDTO.getVideoId() == null){
            return AjaxResult.error("视频id不能为空");
        }
        try {
            // 查询所有的评论和回复评论
            Long allCount = commentService.selectCommentCountByVideoId(commentLimitDTO.getVideoId());
            Map<String,Object> map = new HashMap<>();

            // 用于前端显示（一级+二级）评论的数量
            map.put("commentsChange",allCount);
            if (Objects.isNull(allCount)){
                return AjaxResult.success(map);
            }
            Long userId;
            try {
                 userId = SecurityUtils.getUserId();
            }catch (ServiceException e){
                userId = null;
            }
            List<CommentLikeUser> commentLikeUsers = null;
            // 当用户是游客时，不需要去查询用户是否对评论点赞了
            if (!Objects.isNull(userId)){
                CommentLikeUser commentLikeUser = new CommentLikeUser();
                commentLikeUser.setUserId(userId);
                commentLikeUser.setVideoId(commentLimitDTO.getVideoId());
                commentLikeUsers = commentLikeUserService.selectCommentLikeListByVideoIdAndUserId(commentLikeUser);
            }
            // 一级评论总数
            Long total = commentService.selectCommentCountByVideoIdAndOriginIdIsNull(commentLimitDTO.getVideoId());
            map.put("oneCommentCount",total);
            map.put("commentLikeUsers",commentLikeUsers);
            List<Comment> comment;
            if (commentLimitDTO.getLatest()){// 当latest = true 时表示按时间降序 (默认值：false)selectParentCommentByDateAsc
                comment = commentService.selectCommentByLatest(commentLimitDTO);
            }else {// 用默认排序规则
                comment = commentService.selectCommentByVideoIdAndMaxCount(commentLimitDTO);
            }
            // 改变日期// 改变talk 防止前端回显时属性冲突
            List<Comment> commentList = changeCommentDateAndTalk(comment);
            // 设置子评论
            map.put("commentList", setChildren(commentList,commentLimitDTO.getLatest()));
            return AjaxResult.success(map);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("500",e);
        }
    }


    /**
     * 设置子评论 和 replyTotalCount
     * @param commentList
     * @return
     */
    public List<Comment> setChildren(List<Comment> commentList,boolean latest){
        CommentLimitDTO cDto = new CommentLimitDTO();
        // 添加子评论
        for (int i = 0; i < commentList.size(); i++) {
            cDto.setStartIndex(1);
            cDto.setMaxCount(3);
            cDto.setId(commentList.get(i).getId());
            cDto.setLatest(latest);
            Map<String, Object> commentChildren = commentService.getCommentChildren(cDto);
            if ( Long.parseLong(commentChildren.get("replyTotalCount").toString()) == 0){
                continue;
            }
            commentList.get(i).setReplyTotalCount(Long.parseLong(commentChildren.get("replyTotalCount").toString()));
            commentList.get(i).setChildren((List<Comment>) commentChildren.get("childrenList"));
        }
        return commentList;
    }
    /**
     *  // 改变日期// 改变talk 防止前端回显时属性冲突
     * @param commentList
     * @return
     */
    public List<Comment> changeCommentDateAndTalk(List<Comment> commentList){
        List<Comment> list = new ArrayList<>();
        if (commentList.isEmpty()) {
            return list;
        }
        commentList.forEach(item -> {
            // 改变日期// 改变talk 防止前端回显时属性冲突
            item.setCreatedAtChange(DateChangeUtil.commentDateChange(item.getCreatedAt()));
            item.setTalkCopy(item.getTalk());
        });
        return commentList;
    }

    /***
     * 删除评论
     * @param id 需要删除的评论id
     * @return
     */
    @GetMapping("/deleteComment")
    public AjaxResult deleteComment(Long id, Long originId){
        if(Objects.isNull(id)) {
            return AjaxResult.error("id不能为空");
        }
        int count = commentService.deleteComment(id,originId);
        return AjaxResult.success(count);
    }

    /**
     * 新增评论
     */
    @PostMapping("/addComment")
    public AjaxResult addComment(@RequestBody Comment comment) {
        Comment com = new Comment();
        com.setUserId(SecurityUtils.getUserId());//设置评论者==当前用户
        com.setCreatedAt(new Date());
        com.setTalk(comment.getTalk());
        com.setVideoId(comment.getVideoId());
        if (comment.getId() == null){//新增一级评论
            commentService.insertComment(com);
        }else{// 新增回复
            if (comment.getOriginId() == null){
                com.setOriginId(comment.getId());// 设置一级评论originId
            }else{
                com.setOriginId(comment.getOriginId());
            }
            com.setPid(comment.getId());// 设置回复对象
            commentService.insertComment(com);
        }
        // 返回新增的评论id
        Comment maxId = commentService.selectIdMax();
        return AjaxResult.success(maxId);
    }

    /**
     * 点赞功能
     * @param commentLikeUser
     * @return
     */
    @GetMapping("/updateLike")
    public AjaxResult updateLike(CommentLikeUser commentLikeUser){
        Long userId;
        try {
            userId = SecurityUtils.getUserId();
        }catch (ServiceException e){
            userId = null;
        }
        if (userId == null) return AjaxResult.error("用户未登录");
        commentLikeUser.setUserId(userId);
        int like = commentService.updateLike(commentLikeUser);
        if (like <= 1){
            return AjaxResult.error("事务执行出错");
        }
        return AjaxResult.success(like);
    }


//  --------------------------------------------------

}
